<template>
  <a-modal title="新增" :width="800" :maskClosable="false" v-model="visible" @ok="handleOk">
    <a-form :form="form">
      <a-form-item
        label="品牌名"
        :labelCol="{lg: {span: 7}, sm: {span: 7}}"
        :wrapperCol="{lg: {span: 10}, sm: {span: 17} }"
      >
        <a-input
          v-decorator="[
            'name',
            {initialValue:brand.name,rules: [{ required: true, message: '请输入品牌名' }]}
          ]"
          placeholder="输入品牌名"
        />
      </a-form-item>

      <a-form-item
        label="商品分类"
        :labelCol="{lg: {span: 7}, sm: {span: 7}}"
        :wrapperCol="{lg: {span: 10}, sm: {span: 17} }"
      >
        <a-cascader
          :options="categoryData"
          v-model="categroyValue"
          @change="onCategoryChange"
          placeholder="请选择"
        />
        <div>
          <a-tag
            v-for="(item,index) in selectCategory"
            :key="index"
            closable
            @close="closeTag(item.value)"
          >{{ item.label }}</a-tag>
        </div>
      </a-form-item>

      <a-form-item
        label="是否开启"
        :labelCol="{lg: {span: 7}, sm: {span: 7}}"
        :wrapperCol="{lg: {span: 10}, sm: {span: 17} }"
      >
        <a-radio-group
          v-decorator="[
            'enable',
            {initialValue: brand.enable},
          ]"
        >
          <a-radio :value="true">开启</a-radio>
          <a-radio :value="false">禁用</a-radio>
        </a-radio-group>
      </a-form-item>

      <a-form-item
        label="图片上传"
        :labelCol="{lg: {span: 7}, sm: {span: 7}}"
        :wrapperCol="{lg: {span: 10}, sm: {span: 17} }"
      >
        <a-upload
          name="file"
          listType="picture-card"
          class="avatar-uploader"
          :showUploadList="false"
          :action="uploadUrl"
          :beforeUpload="beforeUpload"
          @change="handleChange"
        >
          <img v-if="imageUrl" :src="imageUrl" alt="avatar" />
          <div v-else>
            <a-icon :type="loading ? 'loading' : 'plus'" />
            <div class="ant-upload-text">Upload</div>
          </div>
        </a-upload>
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script>
import { brandSave, brandUpdate, categoryTree, brandCategorys } from '@/api/product'

export default {
  name: 'BrandModal',
  data () {
    return {
      visible: false,
      brand: {},
      form: this.$form.createForm(this),
      categoryData: [],
      categroyValue: [],
      selectCategory: [],
      uploadUrl: process.env.API_BASE_URL + '/base/upload/image',
      loading: false,
      imageUrl: ''
    }
  },
  methods: {
    handleEdit (record) {
      this.form.resetFields()
      this.brand = Object.assign({}, record)
      this.imageUrl = record.image
      this.loadCategoryData()
      this.loadBrandCategorys({ id: record.id })
      this.categroyValue = []
      this.selectCategory = []
    },
    handleCreate () {
      this.loading = false
      this.categroyValue = []
      this.brand = {
        enable: true
      }
      this.form.resetFields()
      this.loadCategoryData()
      this.selectCategory = []
      this.imageUrl = ''
    },

    // handler
    handleOk () {
      const _this = this
      this.form.validateFields((err, values) => {
        if (!err) {
          const params = { ...values }
          params.id = this.brand.id
          params.image = this.imageUrl
          params.categories = []
          this.selectCategory.forEach(item => {
            params.categories.push({
              id: item.value
            })
          })
          console.log('params:{}: ', params)
          if (!params.id) {
            brandSave(params).then(res => {
              if (res.status === 0) {
                _this.$message.success('保存成功')
                this.visible = false
                _this.$emit('ok')
              } else {
                _this.$message.success(res.msg)
              }
            })
          } else {
            brandUpdate(params).then(res => {
              if (res.status === 0) {
                _this.$message.success('保存成功')
                this.visible = false
                _this.$emit('ok')
              } else {
                _this.$message.success(res.msg)
              }
            })
          }
        }
      })
    },
    loadCategoryData () {
      categoryTree().then(res => {
        const treeData = []
        res.data.forEach(item => {
          const node = {
            label: item.name,
            value: item.id
          }
          setChildren(node, item.children)
          treeData.push(node)
        })
        this.categoryData = treeData
        this.visible = true
      })
    },
    loadBrandCategorys (record) {
      brandCategorys(record).then(res => {
        const temData = []
        res.data.forEach(item => {
          temData.push({
            label: item.name,
            value: item.id
          })
        })
        this.selectCategory = temData
      })
    },

    onCategoryChange (value, selectedOptions) {
      console.log('{},{}', value, selectedOptions)
      if (selectedOptions) {
        const temData = this.selectCategory
        const category = selectedOptions[selectedOptions.length - 1]
        temData.push({
          label: category.label,
          value: category.value
        })
        var map = {}
        this.selectCategory = temData.filter(item => {
          if (!map[item.value]) {
            map[item.value] = true
            return item
          }
        })
      }
    },
    handleChange (info) {
      if (info.file.status === 'uploading') {
        this.loading = true
        return
      }
      if (info.file.status === 'done') {
        // Get this url from response in real world.
        console.log(info)
        this.imageUrl = info.file.response.data.url
        console.log(this.imageUrl)
        this.loading = false
      }
    },
    beforeUpload (file) {
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('Image must smaller than 2MB!')
      }
      return isLt2M
    },
    closeTag (value) {
      console.log(value)
      this.selectCategory = this.selectCategory.filter(item => {
        if (value !== item.value) {
          return item
        }
      })
    }
  },
  created () {},
  watch: {}
}

function setChildren (node, children) {
  if (children) {
    node.children = []
    children.forEach(item => {
      const cNode = {
        label: item.name,
        value: item.id
      }
      setChildren(cNode, item.children)
      node.children.push(cNode)
    })
  }
}
</script>
